/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtWidgets>
#include <qmath.h>
#include <QDebug>
#include "view.h"
#define MAPZOOMCHANGED 0

#ifndef QT_NO_WHEELEVENT
/*delta表示鼠标滚动的距离，该值等于鼠标旋转角度的8倍，正数表示向前，负数表示向后*/


void GraphicsView::wheelEvent(QWheelEvent *e)
{
    if (e->modifiers() & Qt::ControlModifier) {
        if (e->delta() > 0)
            view->zoomIn(10);
        else
            view->zoomOut(10);
        e->accept();
    } else {
        QGraphicsView::wheelEvent(e);
    }
}
#endif

View::View(const QString &name, QWidget *parent)
    : QFrame(parent)
{
    setFrameStyle(Sunken | StyledPanel);/*阴影风格：凹陷，框架外形*/
    MonitorAreaState = false;
    AlertAreaActState = false;




    /*把view作为参数传递给graphicsView*/
    graphicsView = new GraphicsView(this);
    graphicsView->setRenderHint(QPainter::Antialiasing, false);
    graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
    graphicsView->setOptimizationFlags(QGraphicsView::DontSavePainterState);
    graphicsView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
    graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);

    bCursorHandle = true;       //默认是手势
    /*设置为默认工具条的图标大小*/
    int size = style()->pixelMetric(QStyle::PM_ToolBarIconSize);
    QSize iconSize(size, size);

    /*设置缩放的工具条的属性*/
    QToolButton *zoomInIcon = new QToolButton(parent);
//    zoomInIcon->setAutoRepeat(true);//长按时自动重复
//    zoomInIcon->setAutoRepeatInterval(33);
//    zoomInIcon->setAutoRepeatDelay(0);
    zoomInIcon->setIcon(QPixmap(":/zoomin.png"));
    zoomInIcon->setIconSize(iconSize);
    QToolButton *zoomOutIcon = new QToolButton(parent);
//    zoomOutIcon->setAutoRepeat(true);
//    zoomOutIcon->setAutoRepeatInterval(33);
//    zoomOutIcon->setAutoRepeatDelay(0);
    zoomOutIcon->setIcon(QPixmap(":/zoomout.png"));
    zoomOutIcon->setIconSize(iconSize);

    zoomSlider = new QSlider(parent);
    //预留给地图跳级
    zoomSlider->setSingleStep(10);
    zoomSlider->setMinimum(1);
    zoomSlider->setMaximum(200);
    zoomSlider->setValue(50);
    zoomSlider->setTickPosition(QSlider::TicksRight);
    zoomSlider->setTickInterval(10);


    // Zoom slider layout
    QVBoxLayout *zoomSliderLayout = new QVBoxLayout;
    zoomSliderLayout->addWidget(zoomInIcon);
    zoomSliderLayout->addWidget(zoomSlider);
    zoomSliderLayout->addWidget(zoomOutIcon);

    QToolButton *rotateLeftIcon = new QToolButton;
    rotateLeftIcon->setIcon(QPixmap(":/rotateleft.png"));
    rotateLeftIcon->setIconSize(iconSize);
    QToolButton *rotateRightIcon = new QToolButton;
    rotateRightIcon->setIcon(QPixmap(":/rotateright.png"));
    rotateRightIcon->setIconSize(iconSize);
    rotateSlider = new QSlider;
    rotateSlider->setOrientation(Qt::Horizontal);
    rotateSlider->setMinimum(-360);
    rotateSlider->setMaximum(360);
    rotateSlider->setValue(0);
    rotateSlider->setTickPosition(QSlider::TicksBelow);

    // Rotate slider layout
    QHBoxLayout *rotateSliderLayout = new QHBoxLayout;
    rotateSliderLayout->addWidget(rotateLeftIcon);
    rotateSliderLayout->addWidget(rotateSlider);
    rotateSliderLayout->addWidget(rotateRightIcon);

    resetButton = new QToolButton;
    resetButton->setText(tr("Reset"));
    resetButton->setEnabled(false);

    QHBoxLayout *labelLayout = new QHBoxLayout;
    TitleLabel = new QLabel(name);

    //settingbutton
    RadarParameterButton = new QToolButton;
    RadarParameterButton->setText(tr("RadarSetting"));
    RadarParameterButton->setCheckable(true);
    RadarParameterButton->setChecked(false);

    /////new
    //地图设置
//    MapParameterButton = new QToolButton;
//    MapParameterButton->setText(tr("MapSetting"));
//    MapParameterButton->setCheckable(true);
//    MapParameterButton->setChecked(false);

    //identifytrack
    identifyTrackButton = new QToolButton;
    identifyTrackButton->setText(tr("TrackSetting"));
    identifyTrackButton->setCheckable(true);
    identifyTrackButton->setChecked(false);

    clearTargetButton = new QToolButton;
    clearTargetButton->setText(tr("Clear"));
    clearTargetButton->setCheckable(true);
    clearTargetButton->setChecked(false);

    labelLayout->addWidget(TitleLabel);
    labelLayout->addStretch();
    labelLayout->addWidget(RadarParameterButton);
    labelLayout->addWidget(identifyTrackButton);
    labelLayout->addWidget(clearTargetButton);

    // main layout
    QGridLayout *topLayout = new QGridLayout;
    topLayout->addLayout(labelLayout, 0, 0);
    topLayout->addWidget(graphicsView, 1, 0);
    topLayout->addLayout(zoomSliderLayout, 1, 1);
    topLayout->addLayout(rotateSliderLayout, 2, 0);
    topLayout->addWidget(resetButton, 2, 1);
    setLayout(topLayout);
    graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);


#if MAPZOOMCHANGED
    MapChangeButton = new QToolButton;
    QPixmap pixmap(100,100);//准备装图片的矩形框
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    QPainterPath path;
    path.addRoundedRect(0,0,100, 100,0,0);//绘制圆角矩形,x轴y轴半径都为15
    painter.setClipPath(path);
    painter.drawPixmap(0, 0, 100, 100, QPixmap(":/Map3D.png"));//将显示图片的pixmap画入矩形框内
    MapChangeButton->setIcon(pixmap);
    MapChangeButton->setIconSize(QSize(100,100));
//    MapChangeButton->setStyleSheet("border:none");
    m_bMapChange = 1;             //初始化为3D

    Scalelabel = new QLabel;
    QPixmap pixmap1(145,118);//准备装图片的矩形框
    pixmap1.fill(Qt::transparent);
    QPainter painter1(&pixmap1);
    painter1.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    QPainterPath path1;
    path1.addRoundedRect(0,0,145, 118,0,0);//绘制矩形
    painter1.setClipPath(path1);
    QPixmap pixmap2(QString(":/scale/scale%1.png").arg(QString::number(m_u32zoom)));
    painter1.drawPixmap(0, 0, pixmap2.width(), pixmap2.height(), pixmap2);//将显示图片的pixmap画入矩形框内
    Scalelabel->setPixmap(pixmap1);
    Scalelabel->setStyleSheet("border:none");
    topLayout->addWidget(MapChangeButton, 1, 0, Qt::AlignLeft | Qt::AlignTop);
    topLayout->addWidget(Scalelabel, 1, 0, Qt::AlignRight | Qt::AlignBottom);

    connect(resetButton, SIGNAL(clicked()), parent, SLOT(resetpMap()));
    connect(zoomSlider, SIGNAL(valueChanged(int)), parent, SLOT(setupMap(int)));
    connect(this, SIGNAL(emitmapchange(bool)), parent, SLOT(MapChangeOp(bool)));
    connect(MapChangeButton, SIGNAL(clicked(bool)), this, SLOT(ButtonChangeIcon()));
#endif

//    connect(MapParameterButton, SIGNAL(clicked(bool)), this, SLOT(MapSetting()));
    connect(resetButton, SIGNAL(clicked()), this, SLOT(resetView()));
    connect(zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix()));
    connect(rotateSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix()));
    connect(graphicsView->verticalScrollBar(), SIGNAL(valueChanged(int)),
            this, SLOT(setResetButtonEnabled()));
    connect(graphicsView->horizontalScrollBar(), SIGNAL(valueChanged(int)),
            this, SLOT(setResetButtonEnabled()));
    connect(RadarParameterButton, SIGNAL(clicked(bool)), this, SLOT(toggleSetting()));
    connect(identifyTrackButton, SIGNAL(clicked(bool)), this, SLOT(toogleTrackSetting()));
    connect(clearTargetButton, SIGNAL(clicked(bool)), this, SLOT(emittomap()));

    connect(rotateLeftIcon, SIGNAL(clicked()), this, SLOT(rotateLeft()));
    connect(rotateRightIcon, SIGNAL(clicked()), this, SLOT(rotateRight()));
    connect(zoomInIcon, SIGNAL(clicked()), this, SLOT(zoomIn()));
    connect(zoomOutIcon, SIGNAL(clicked()), this, SLOT(zoomOut()));





    setupMatrix();
}

QGraphicsView *View::view() const
{
    return static_cast<QGraphicsView *>(graphicsView);
}

void View::resetView()
{
    zoomSlider->setValue(50);
    rotateSlider->setValue(0);
    setupMatrix();
    graphicsView->ensureVisible(QRectF(0, 0, 0, 0));
    resetButton->setEnabled(false);
}

void View::setResetButtonEnabled()
{
    resetButton->setEnabled(true);
}

void View::setupMatrix()
{
    qreal scale = qPow(qreal(2), (zoomSlider->value() - 50) / qreal(50));//以2的次幂进行缩放

    QMatrix matrix;
    matrix.scale(scale, scale);
    matrix.rotate(rotateSlider->value());

    graphicsView->setMatrix(matrix);
    resetButton->setEnabled(true);
    emit emitscalechanged(scale);
}

//设置雷达参数
void View::toggleSetting()
{
    emit setRadarParameter();
    RadarParameterButton->setChecked(false);
}

//设置地图位置
void View::MapSetting()
{
    emit setMapParameter();
    RadarParameterButton->setChecked(false);
}

void View::TriggeredMonitorArea(bool flag)
{
    if(flag){
        MonitorAreaState = true;
        graphicsView->setDragMode(QGraphicsView::NoDrag);  //视图漫游
        graphicsView->setCursor(Qt::CrossCursor);
        emit triggeredMonitorAreaSig();
        emit triggeredAreaSignal(MonitorArea);
    }
    else
    {
        MonitorAreaState = false;
        graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);  //视图漫游
        graphicsView->setCursor(Qt::ArrowCursor);
    }
}

void View::TriggeredAlertArea(bool flag)
{
    if(flag){
        graphicsView->setDragMode(QGraphicsView::NoDrag);  //视图漫游
        graphicsView->setCursor(Qt::CrossCursor);
        AlertAreaActState = true;
        emit triggeredAlertAreaSig();
        emit triggeredAreaSignal(AlertArea);
    }
    else
    {
        graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);  //视图漫游
        graphicsView->setCursor(Qt::ArrowCursor);
        AlertAreaActState = false;
    }
}

//清理所有item
void View::emittomap()
{
    emit clearMap();
    clearTargetButton->setChecked(false);
}

//航迹设置
void View::toogleTrackSetting()
{
    emit setTrack();
    identifyTrackButton->setChecked(false);
}

void View::selectArea()
{
    graphicsView->setDragMode(QGraphicsView::NoDrag);
    graphicsView->setCursor(Qt::CrossCursor);
    bCursorHandle = false;   //改为十字
}

void View::zoomIn(int level)
{
    zoomSlider->setValue(zoomSlider->value() + level);
}

void View::zoomOut(int level)
{
    zoomSlider->setValue(zoomSlider->value() - level);
}

void View::rotateLeft()
{
    rotateSlider->setValue(rotateSlider->value() - 10);
}

void View::rotateRight()
{
    rotateSlider->setValue(rotateSlider->value() + 10);
}

void View::contextMenuEvent(QContextMenuEvent *e)
{
    if(MonitorAreaState || AlertAreaActState)
    {
        MonitorAreaState  = false;                                 //右键恢复手势和拖拽
        AlertAreaActState = false;
        graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);  //视图漫游
        graphicsView->setCursor(Qt::ArrowCursor);
    }
    else
    {
        //启动菜单
        creatActions();
        creatMenus();
        connect(MonitorAreaAct, SIGNAL(triggered(bool)), this, SLOT(TriggeredMonitorArea(bool)));
        connect(AlertAreaAct, SIGNAL(triggered(bool)), this, SLOT(TriggeredAlertArea(bool)));
        mainMenu->exec(QCursor::pos());

#if 0
        QMenu* pMenu = new QMenu(this);
        QAction *pAction0 = new QAction("地图设置", this);
        QAction *pAction1 = new QAction("雷达设置", this);//setting
        QAction *pAction2 = new QAction("跟踪设置", this);//trace
        QAction *pAction3 = new QAction("清除航迹", this);//clear
        QAction *pAction4 = new QAction("选择区域", this);//select

        pMenu->addAction(pAction0);
        pMenu->addAction(pAction1);
        pMenu->addAction(pAction2);
        pMenu->addAction(pAction3);
        pMenu->addAction(pAction4);
        connect(pAction0, SIGNAL(triggered()), this, SLOT(MapSetting()));
        connect(pAction1, SIGNAL(triggered()), this, SLOT(toggleSetting()));
        connect(pAction2, SIGNAL(triggered()), this, SLOT(toogleTrackSetting()));
        connect(pAction3, SIGNAL(triggered()), this, SLOT(emittomap()));
        connect(pAction4, SIGNAL(triggered()), this, SLOT(selectArea()));

        pMenu->exec(QCursor::pos());
#endif
        //delete pMenu;
    }
}

bool View::GetCursorHandle()
{
    return bCursorHandle;
}


View::creatActions()
{
    MonitorAreaAct = new QAction(tr("监测区域"), this);
    MonitorAreaAct->setStatusTip(tr("请设置监测区域"));
    MonitorAreaAct->setCheckable(true);
    //!connect


    AlertAreaAct = new QAction(tr("警戒区域"), this);
    AlertAreaAct->setStatusTip(tr("请设置警戒区域"));
    AlertAreaAct->setCheckable(true);
    //!connect

    RadarLocationAct = new QAction(tr("雷达定位"), this);
    RadarLocationAct->setStatusTip(tr("请在地图上选择雷达位置"));
    RadarLocationAct->setCheckable(true);
    //!connect
    //!
}

View::creatMenus()
{
    mainMenu = new QMenu(this);
    mainMenu->addAction(RadarLocationAct);
    mainMenu->addSeparator();
    AreaSelectionMenu = mainMenu->addMenu(tr("区域选择"));
    AreaSelectionMenu->addAction(MonitorAreaAct);
    AreaSelectionMenu->addAction(AlertAreaAct);
}

















GraphicsScene::GraphicsScene(QWidget *parent)
{
    MonitorAreaSelected = false;
    AlertAreaSelected = false;
}

GraphicsScene::~GraphicsScene()
{

}

void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{    
    if(event->button() == Qt::LeftButton)
    {
        if(MonitorAreaSelected)
        {
            qDebug() << "MonitorArea triggered!";
            emit MonitorAreaSelecting(event->scenePos());
            emit AreaSelecting(event->scenePos(), MonitorArea);
        }
        else{}

        if(AlertAreaSelected)
        {
            qDebug() << "AlertArea triggered!";
            emit AlertAreaSelecting(event->scenePos());
            emit AreaSelecting(event->scenePos(), AlertArea);
        }
        else{}
    }
    else if (event->button() == Qt::RightButton)
    {
        if(MonitorAreaSelected){
            emit MonitorAreaFinish();
            emit AreaFinished(MonitorArea);
            MonitorAreaSelected = false;
            qDebug()<<"MonitorArea Exit!";
        }
        else{}

        if(AlertAreaSelected){
            emit AlertAreaFinish();
            emit AreaFinished(AlertArea);
            AlertAreaSelected = false;
            qDebug()<<"AlertArea Exit!";
        }
        else{}
    }
}

void GraphicsScene::getMonitorAreaFlag()
{
    MonitorAreaSelected = true;
}

void GraphicsScene::getAlertAreaFlag()
{
    AlertAreaSelected = true;

}

void GraphicsScene::getAreaType(AreaType type)
{
    switch (type) {
    case MonitorArea:
    {
        MonitorAreaSelected = true;
        break;
    }
    case AlertArea:
    {
        AlertAreaSelected = true;
    }
    default:
        break;
    }
}

